package loader.core
{
	import flash.display.Loader;
	import flash.utils.ByteArray;
	import loader.core.load.BaseLoader;
	import loader.core.load.ResLoader;
	import loader.core.load.ResParse;
	//加载资源队列服务器
	public class BaseServer 
	{
		private var loaderArray:Vector.<BaseLoader> = new Vector.<BaseLoader>();//资源加载器队列
		public var fileArray:Vector.<LoadFile> = new Vector.<LoadFile>();//要加载处理的文件
		private var serverType:int;//服务器类型
		public var comHandler:Function;//单个文件加载完后处理
		public var proessHandler:Function;//单个文件加载进度处理
		public var max:int = 1;
		
		public function BaseServer(type:int,comHandler:Function,proessHandler:Function = null,max:int = 5)
		{
			this.serverType = type;
			this.comHandler = comHandler;
			this.proessHandler = proessHandler;
			this.max = max;
			initLoaders();
		}
		
		public function initLoaders():void{
			for(var i:int=0;i<max;i++){
				switch(this.serverType){
					case LoadType.RES_SERVER:
						loaderArray[i] = new ResLoader(this);
						break;
					case LoadType.PAR_SERVER:
						loaderArray[i] = new ResParse(this);
						break;
				}
			}
		}
		
		//加载资源
		public function load(file:LoadFile):void{
        	//开始加载
			var loader:BaseLoader = getIdleLoader();
        	if(loader != null){
        		loader.loadFile(file);
        	}else{
        		fileArray.push(file);
        	}
        	
		}
		
		
		//获得空闲的加载器
        public function getIdleLoader():BaseLoader{
			for(var i:int=0;i<loaderArray.length;i++){
        		if(loaderArray[i].isLoading == false){
        			return loaderArray[i];
        		}
        	}
        	return null;
		}
		
		//销毁所有的加载器
		public function destory():void{
        	fileArray.length = 0;
        	for(var i:int=0;i<loaderArray.length;i++){
        		if(loaderArray[i].isLoading == true){
        			BaseLoader(loaderArray[i]).destory();
        		}
        	} 
        }
		
		//加载状态
		public function sendStatus(message:String):void {
			trace("load",message);
		}
		
		
		private var loader:Loader;
		private var temp:Vector.<String>;//防硕思破解 只能防5.0以下版本
		private var seed:Array = [0xD83EFCAB,0xB34CABE6,0xF74ECAB8,0xCABBC2A3,0xBACF0CD9,0xDFBB07F9,0xC66FACB8,0xB1F9DE96,0xAB95CCAB];
		public function decode(targetBytes:ByteArray):ByteArray{
			if(LoadType.LOAD_TYPE == LoadType.NORMAL_LOAD){
				//正常加载
			}else if(LoadType.LOAD_TYPE == LoadType.MD5_LOAD){
				//todo:对处理的文件，解码
				var byteArray:ByteArray = new ByteArray();
	        	var n:int=0;
	            
				while (targetBytes.bytesAvailable>=4) {
					byteArray.writeInt(targetBytes.readInt()^seed[n%9]);
					n++;
				}
				if(targetBytes.bytesAvailable>0){
					var leaveBytes:ByteArray = new ByteArray();
					targetBytes.readBytes(leaveBytes);
					byteArray.writeBytes(leaveBytes);
				}
				return byteArray;
			}
			return targetBytes;
		}
	}
}